package run.microservice.stock.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.stereotype.Component;
import org.springframework.util.StringValueResolver;

import java.util.Optional;

/**
 * @author lunfangyu
 */
@Slf4j
@Component
public class SpringContextUtil implements ApplicationContextAware, EmbeddedValueResolverAware {
    private static ApplicationContext applicationContext = null;
    private static StringValueResolver stringValueResolver = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(SpringContextUtil.applicationContext == null) {
            SpringContextUtil.applicationContext = applicationContext;
        }
    }

    @Override
    public void setEmbeddedValueResolver(StringValueResolver stringValueResolver) {
        SpringContextUtil.stringValueResolver = stringValueResolver;
    }

    /**
     * 通过name获取 Bean
     * @param name
     * @return
     */
    public static Object getBean(String name){
        return applicationContext.getBean(name);
    }

    /**
     * 通过class获取Bean
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz){
        return applicationContext.getBean(clazz);
    }

    /**
     * 通过name以及Clazz返回指定的Bean
     * 适用于有子类的Bean, 当需要获取父类时，如果只指定类型会报错；这里就需要同时指定类型和名称
     * @param name
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name, Class<T> clazz){
        return applicationContext.getBean(name, clazz);
    }


    /**
     * 动态获取配置文件中的值
     * @param property
     * @return
     */
    public static String getPropertiesValue(String property) {

        try {
            String name = "${" + property + "}";
            return stringValueResolver.resolveStringValue(name);
        } catch (Exception e) {
            log.error(String.format("当前环境变量中没有[%s]的配置", property), e);
        }
        return "";
    }

    public static <T> Optional<T> getBeanBy(Class<T> clazz) {
        try {
            T bean = applicationContext.getBean(clazz);
            return Optional.ofNullable(bean);
        } catch (Exception e) {
            log.error(String.format("找不到实例：%s", clazz), e);
            return Optional.empty();
        }
    }
}
